const uuid = require('uuid');
const moment = require('moment');

// 打乱数组
async function shuffle (arr, start, length) {
    for (let i = length - 1; i >= start; i--) {
        let rIndex = Math.floor(Math.random() * (i - start + 1)) + start;
        let temp = arr[rIndex];
        arr[rIndex] = arr[i];
        arr[i] = temp;
    }
    return arr;
}

function fillNumberPrefix (num, val) {
    return (new Array(num).join('0') + val).slice(-num);
}

function generateRandomString () {
    return Math.random().toString(36).substr(2);
}

function generateRandomUUID () {
    return uuid.v1().toString().replace(/-/g, '').toString();
}

function getRandomNumberInRange (min, max) {
    // [min, max]
    return Math.round(Math.random() * (max - min)) + min;
}

function validPhone (str) {
    const reg = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
    return reg.test(str);
}

/**
 * 从数组中随机获取n个元素
 * @param arr
 * @param count
 * @returns {*}
 */
function getRandomArrayElements (arr, count) {
    let shuffled = arr.slice(0);
    let i = arr.length;
    let min = i - count;
    let temp;
    let index;

    if (i < count) {
        while (--i && i >= 0) {
            index = Math.floor(Math.random() * i);
            temp = shuffled[i];
            shuffled[i] = shuffled[index];
            shuffled[index] = temp;
        }
        return shuffled;
    }

    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}

function generateRandomOrderIdWithTime () {
    const timeInfo = moment().format('YYYYMMDDHHmmssSSS');
    const randomNumber = Math.random();
    const suffix = randomNumber.toString().split('.')[1].slice(0, 4);
    return timeInfo + suffix;
}

function generateRandomChargeOrderIdWithTime () {
    const timeInfo = moment().format('YYYYMMDDHHmmssSSS');
    const randomNumber = Math.random();
    const suffix = randomNumber.toString().split('.')[1].slice(0, 6);
    return timeInfo + suffix;
}
module.exports = {
    shuffle,
    fillNumberPrefix,
    generateRandomString,
    generateRandomUUID,
    getRandomNumberInRange,
    validPhone,
    getRandomArrayElements,
    generateRandomOrderIdWithTime,
    generateRandomChargeOrderIdWithTime
};
